// ==UserScript==
// @name         UCManager
// @description  rebuild_userChrome.uc.xul的替代品
// @namespace    1018148046
// @author       颜太吓
// @include      chrome://browser/content/browser.xul
// @version      0.1
// @charset      UTF-8
// ==/UserScript==
(function() {
	'use strict';
	window.ECM = {
		//需要移动的菜单id,移到到功能菜单内
		menues: ['ucjsMouseGestures', 'redirector-icon'],
		addmenuitem: function() {
			let Folderimg = 'chrome://userchromejs/content/icons/other/16x16.svg#folder';
			let Editimg = 'chrome://userchromejs/content/icons/other/16x16.svg#edit';
			let Profilesimg = 'chrome://userchromejs/content/icons/other/16x16.svg#Profiles';
			let mp = $('ecm-popup');
			let ucmenu = mp.appendChild($C('menu', {
				label: '功能菜单',
				class: 'menu-iconic',
				image: 'chrome://userchromejs/content/icons/other/16x16.svg#ucmenu'
			}));
			let ucmenupop = ucmenu.appendChild($C('menupopup', {
				id: 'ucmenu-popup'
			}));
			let list = [{
				label: "打开文件",
				image: "chrome://userchromejs/content/icons/other/16x16.svg#open",
				items: [{
					label: "打开Chrome",
					oncommand: 'ECM.exec(ECM.folder(1))',
					image: Folderimg
				}, {
					label: "打开Profile",
					oncommand: 'ECM.exec(ECM.folder(0))',
					image: Folderimg
				}, {
					label: "EDGE中打开",
					oncommand: 'ECM.exec("C:\\\\WINDOWS\\\\explorer.exe","microsoft-edge:"+ gBrowser.currentURI.spec)',
					image: 'chrome://userchromejs/content/icons/other/16x16.svg#edge'
				}, {
					label: "IE中打开",
					oncommand: 'ECM.exec("C:\\\\Program Files\\\\Internet Explorer\\\\iexplore.exe"," -private " + gBrowser.currentURI.spec)',
					image: 'chrome://userchromejs/content/icons/other/16x16.svg#ie'
				}, ]
			}, {
				label: "配置多开",
				image: Profilesimg,
				items: [{
					label: "测试配置1",
					oncommand: 'ECM.exec(ECM.folder(0) + "\\\\..\\\\Firefox\\\\firefox.exe","-no-remote -profile ..\\\\Profiles1")',
					image: Profilesimg
				}, {
					label: "测试配置2",
					oncommand: 'ECM.exec(ECM.folder(0) + "\\\\..\\\\Firefox\\\\firefox.exe","-no-remote -profile ..\\\\Profiles2")',
					image: Profilesimg
				}, {
					label: "测试配置3",
					oncommand: 'ECM.exec(ECM.folder(0) + "\\\\..\\\\Firefox\\\\firefox.exe","-no-remote -profile ..\\\\Profiles3")',
					image: Profilesimg
				}, {
					label: "测试配置4",
					oncommand: 'ECM.exec(ECM.folder(0) + "\\\\..\\\\Firefox\\\\firefox.exe","-no-remote -profile ..\\\\Profiles4")',
					image: Profilesimg
				}, ]
			}, {
				label: "编辑文件",
				image: Editimg,
				items: [{
					label: "userChrome",
					oncommand: 'ECM.edit(ECM.folder(1)+"\\\\userChrome.js")',
					image: Editimg
				}, {
					label: "UCManager",
					oncommand: 'ECM.edit(ECM.folder(1)+"\\\\UCManager.uc.js")',
					image: Editimg
				}, {
					label: "prefs.js",
					oncommand: 'ECM.edit(ECM.folder(0)+"\\\\prefs.js")',
					image: Editimg
				}, {
					label: "user.js",
					oncommand: 'ECM.edit(ECM.folder(0)+"\\\\user.js")',
					image: Editimg
				}, ]
			}, ];
			for (let i = 0; i < list.length; i++) {
				let m = mp.appendChild($C('menu', {
					label: list[i].label,
					image: list[i].image,
					class: 'menu-iconic'
				}));
				let pop = m.appendChild($C('menupopup'));
				for (let j = 0; j < list[i].items.length; j++) {
					let mi = $C("menuitem", {
						label: list[i].items[j].label,
						image: list[i].items[j].image,
						oncommand: list[i].items[j].oncommand,
						class: 'menuitem-iconic'
					});
					pop.appendChild(mi);
				}
			}
		},
		addbtn: function() {
			let aPopup = $C('menupopup', {
				id: 'ecm-popup',
				position: 'after_start',
				onclick: 'event.preventDefault(); event.stopPropagation();'
			});
			aPopup.addEventListener('popupshowing', (event) => ECM.onpopup(event));
			aPopup.addEventListener('popuphiding', (event) => ECM.hidepopup(event));
			$('mainPopupSet').appendChild(aPopup);
			try {
				CustomizableUI.createWidget({
					id: 'ExtrasConfigMenu',
					type: 'custom',
					defaultArea: CustomizableUI.AREA_NAVBAR,
					onBuild: function(aDocument) {
						let toolbarbutton = aDocument.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'toolbarbutton');
						let attributes = {
							id: 'ExtrasConfigMenu',
							class: 'toolbarbutton-1',
							removable: 'true',
							onclick: 'ECM.onClick(event)',
							label: 'UC管理器',
							tooltiptext: '中键:重载UC脚本\n右键:重启浏览器',
							type: 'menu',
							popup: "ecm-popup"
						};
						for (let a in attributes)
						toolbarbutton.setAttribute(a, attributes[a]);
						return toolbarbutton;
					}
				})
			} catch (e) {};
		},
		onClick: function(event) {
			if (event.button === 2) {
				Services.appinfo.invalidateCachesOnRestart();
				('BrowserUtils' in window) ? BrowserUtils.restartApplication() : Application.restart();
			}
		},
		onpopup: function(event) {
			let mp = event.target;
			if (mp.id != "ecm-popup") {
				return;
			}
			if (mp.triggerNode) {
				mp.triggerNode.setAttribute('open', 'true');
			}
			if (mp !== event.currentTarget) {
				return;
			}
		},
		hidepopup: function(event) {
			let mp = event.target;
			if (mp.id != "ecm-popup") {
				return;
			}
			if (mp.triggerNode) {
				mp.triggerNode.removeAttribute('open');
			}
		},
		UCmenu: function() {
			let mp = $('ecm-popup');
			let sep = $C('menuseparator', {
				class: 'uc-menuseparator'
			});
			mp.appendChild(sep);
			for (let i = 0, leni = userChrome_js.UCfiles.length; i < leni; i++) {
				if (userChrome_js.UCfiles[i].file.length != 0) {
					let foldername = userChrome_js.UCfiles[i].folder;
					let menu = mp.appendChild($C("menu", {
						class: "menu-iconic uc-menu",
						image: "chrome://userchromejs/content/icons/other/UC.svg#UC",
						label: foldername
					}));
					let ucmp = menu.appendChild($C("menupopup"));
					let scripts = userChrome_js.UCfiles[i].file;
					for (let j = 0, leni = scripts.length; j < leni; j++) {
						let scriptname = userChrome_js.UCfiles[i].file[j].scriptname;
						let scriptpath = userChrome_js.UCfiles[i].file[j].scriptpath;
						let mi = ucmp.appendChild($C("menuitem", {
							label: scriptname.replace(/\.uc\.js$|\.uc\.xul$/g, ''),
							onclick: "ECM.clickScriptMenu(event);",
							type: "checkbox",
							checked: userChrome_js.disablescript.indexOf(scriptname) == -1,
							oncommand: 'ECM.chgScriptStat("' + scriptname + '")'
						}));
						mi.scriptpath = scriptpath;
					}
				}
			}
		},
		chgScriptStat: function(scriptname) {
			var s = Preferences.get('userChrome.disable.script');
			if (userChrome_js.disablescript.indexOf(scriptname) == -1) {
				s = (s + ',').replace(scriptname + ',', '') + scriptname + ',';
			} else {
				s = (s + ',').replace(scriptname + ',', '');
			}
			s = s.replace(/,,/g, ',').replace(/^,/, '');
			Preferences.set('userChrome.disable.script', s);
			userChrome_js.disablescript = s;
		},
		clickScriptMenu: function(event) {
			let target = event.target;
			let scriptpath = target.scriptpath;
			if (event.button === 2) {
				this.edit(scriptpath);
			}
		},
		exec: function(path, arg) {
			let file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsILocalFile);
			let process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess);
			let a;
			if (typeof arg == 'string' || arg instanceof String) {
				a = arg.split(/\s+/)
			} else if (Array.isArray(arg)) {
				a = arg;
			} else {
				a = [arg];
			}
			file.initWithPath(path);
			if (!file.exists()) {
				Cu.reportError('File Not Found: ' + path);
				return;
			}
			if (file.isExecutable()) {
				process.init(file);
				process.runw(false, a, a.length);
			} else {
				file.launch();
			}
		},
		folder: function(key) {
			switch (key) {
			case 0:
				var path = Services.dirsvc.get("ProfD", Ci.nsILocalFile).path;
				break;
			case 1:
				var path = Services.dirsvc.get("UChrm", Ci.nsILocalFile).path;
				break;
			}
			return path;
		},
		edit: function(path) {
			let vieweditor = Services.prefs.getCharPref('view_source.editor.path');
			let UI = Cc['@mozilla.org/intl/scriptableunicodeconverter'].createInstance(Ci.nsIScriptableUnicodeConverter);
			UI.charset = window.navigator.platform.toLowerCase().indexOf('win') >= 0 ? 'gbk' : 'UTF-8';
			if (!vieweditor) {
				alert('请先设定编辑器路径!!!');
			}
			this.exec(Services.prefs.getCharPref('view_source.editor.path'), path);
		},
		moveMenu: function() {
			let i, Item;
			let ucmenupopup = $('ucmenu-popup');
			for (i = 0; i < this.menues.length; i++) {
				Item = $(this.menues[i]);
				if (Item != null) ucmenupopup.appendChild(Item);
			};
			if ($('gm_general_menu') != null) {
				ucmenupopup.appendChild($('gm_general_menu'));
				$('gm_general_menu').setAttribute("image", "chrome://userchromejs/content/icons/other/16x16.svg#gm");
			};
			if ($('stylish-popup') != null) {
				let Stylish = ucmenupopup.appendChild($C('menu', {
					label: 'Stylish',
					class: 'menu-iconic',
					image: 'chrome://userchromejs/content/icons/other/16x16.svg#stylish'
				}));
				let stylishpopup = $('stylish-popup').cloneNode(true);
				stylishpopup.removeAttribute("position");
				stylishpopup.removeAttribute("onpopuphiding");
				stylishpopup.setAttribute("onpopuphiding", 'var popup = event.target;if (popup.id != "stylish-popup") {return;}stylishOverlay.clearStyleMenuItems(event);');
				Stylish.appendChild(stylishpopup);
			};
		},
		addstyle: function() {
			let style = ' \
        @namespace url(http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul); \
        #ExtrasConfigMenu[cui-areatype="toolbar"] .toolbarbutton-icon {\
          list-style-image: url(chrome://userchromejs/content/icons/other/UC.svg#UC);\
        }\
        #TabsToolbar #ExtrasConfigMenu[cui-areatype="toolbar"] .toolbarbutton-icon {\
          list-style-image: url(chrome://userchromejs/content/icons/other/UC.svg#UC-inverted);\
        }\
        #ExtrasConfigMenu[cui-areatype="menu-panel"] .toolbarbutton-icon, toolbarpaletteitem[place="palette"]> #ExtrasConfigMenu .toolbarbutton-icon {\
          list-style-image: url(chrome://userchromejs/content/icons/other/UC-32.svg);\
        }\
        #ecm-popup > .uc-menu {\
          -moz-box-ordinal-group:999;\
        }\
        #ecm-popup > .uc-menuseparator {\
          -moz-box-ordinal-group:998;\
        }\
        #ecm-popup > .uc-menu > menupopup > menuitem:not([checked="true"]) {\
          -moz-box-ordinal-group:998;\
          color:#999;\
        }\
        #ecm-popup > .uc-menu > menupopup > .UCManager {\
          -moz-box-ordinal-group:999;\
        }\
        '.replace(/\s+/g, " ");
			let sspi = document.createProcessingInstruction('xml-stylesheet', 'type="text/css" href="data:text/css,' + encodeURIComponent(style) + '"');
			document.insertBefore(sspi, document.documentElement);
		},
		init: function() {
			this.addbtn();
			this.addstyle();
			this.UCmenu();
			this.addmenuitem();
			this.moveMenu();
		},
	};
	window.ECM.init();

	function $(id) {
		return document.getElementById(id);
	}

	function $C(name, attr) {
		var el = document.createElement(name);
		if (attr) Object.keys(attr).forEach(function(n) el.setAttribute(n, attr[n]));
		return el;
	}
}());